function send(formId) {
    if (trim($("#chatText").val()) == "") {
        return false;
    }
    ajaxStart();
    var url = sendUrl;
    $.ajax({
        type: "POST",
        url: url,
        async: true,
        timeout: 15000, // 30 secondes
        data: $("#" + formId).serialize(), // serializes the form's elements.
        success: function(data) {
            parseSend(data);
            ajaxStop();
        //alert(data); // show response from the php script.
        },
        complete: function(a) {
            //console.log(a);
            ajaxStop();
        }
    });
    return false;
}

function parseSend(data) {
    var jSonTable = eval("(" + data + ")");
    for (i = 0; i < jSonTable.status.length; i++) {
        $(".statut" + jSonTable.status[i].id).each(function(index) {
            $(this).attr("src", imgUrl + jSonTable.status[i].statut + ".png");
        });
    }
    insertDiscussion(jSonTable.discussion, 'fade');
}

function update(notifNbr) {
    var url = whatsUpUrl + "" + notifNbr;
    $.ajax({
        cache: false,
        timeout: 600000, // 10 minutes
        type: "POST",
        url: url,
        error: function(err) {
            setTimeout(update, 60000); //après1min
        },
        success: function(response) {
            var jSonTable = eval("(" + response + ")");
            if (jSonTable.notifsNumber != -1) {
                notifNbr = trim(jSonTable.notifsNumber);
                $("#notifs").html(jSonTable.notifsNumber);
                $("[id^='ntf']").html("");
                $.each(jSonTable.ntfByUser, function(i, l) {
                    $("#ntf" + l.from_user).html(l.nbr_ntfs);
                });
            }
            if (notifNbr > 0) {
                getNews();       //Joseph : 06 68 40 59 36
            }
            setTimeout(function() {
                update(notifNbr);
            // alert(notifNbr)
            }, 1000); //après 1 sec
        }
    });
}

function getNews() {
    ajaxStart();
    var withId = $("#withId").val();
    $.ajax({
        async: true,
        cache: false,
        timeout: 600000, // 10 minutes
        type: "POST",
        url: newsUrl + "/" + withId,
        error: function() {
            ajaxStop();
        //console.log("error occurred");
        },
        success: function(data) {
            //console.log("data="+data);
            ajaxStop();
            //console.log("parsing data ..");
            parseNews(data);
        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

//parse News returned as Json
function parseNews(data) {
    //alert(data);
    var jSonTable = eval("(" + data + ")");
    //console.log(jSonTable);
    $.each(jSonTable, function(i, l) {
        //console.log(l);
        var from_user = l.object.from_user.id;
        //triming ;
        from_user = trim(from_user);
        withId = $("#withId").val();
        console.log("user=" + from_user + " with=" + withId)
        if (from_user == withId) {
            insertDiscussion(l.object, 'hightlight');
        }
    });
//   
//    $( ".statut"+ withId ).each(function(index) {
//        $(this).attr("src",imgUrl+jSonTable.object.to_user.statut+".png");
//        alert(index);
//    });
}

function ajaxStart() {
//    $("#ajax-loader").show();
}

function ajaxStop() {
//    $("#ajax-loader").hide();
//alert("done.")
}

function trim(str) {
    return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

function loadChatWith(withId) {
    if (withId === "")
        return;
    url = withUrl;
    ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: {
            withId: withId
        },
        error: function() {
            ajaxStop();
        //console.log("error occurred");
        },
        success: function(data) {
            ajaxStop();

            //console.log("parsing data for with ..");
            console.log(data);

            parseWith(data);
            $("#withId").val(withId);
            selectUser(withId);

        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

function selectUser(id) {
    $("[id^='divUser']").removeClass("selected");
    $("#divUser" + id).toggleClass("selected");
}

function parseWith(data) {
    //console.log(data);
    var jSonObject = eval("(" + data + ")");
    var dtMin = jSonObject.dtMin;
    //    console.log(jSonObject);
    //    alert("see console !")
    var newConnection = "<div class=\"span1\" style=\" height: 60px; width:59px\">" +
    "<a href=\"javascript:loadChatWith('" + jSonObject.to_user.id + "');\">" +
    "<div style=\"position: relative; width:100%\">" +
    "<img id=\"divUser" + jSonObject.to_user.id + "\" style=\"position:absolute\" src=\""
    + tofsUrl + jSonObject.to_user.tof + "\">"
    + "<img class=\"statut" + jSonObject.to_user.id + "\" title=\""
    + jSonObject.to_user.statut
    + "\" style=\"position:absolute; width: 9px; height:9px; margin-left:41px; z-index: 1000;\" src=\"" +
    imgUrl + jSonObject.to_user.statut + ".png\">" +
    "</div>" +
    "</a>" +
    "</div>";

    //    console.log(newConnection)
    $("#discussion").html("<center class='aToRemove'><a href=\"javascript:loadPlus('" + dtMin + "')\"> Load Plus </a></center>");
    $("#chatingWith").html("");
    htmlChatingWith = getUserDiv(jSonObject);
    //console.log(htmlChatingWith);
    $("#chatingWith").html(htmlChatingWith);
    $("#first_name_with").html(jSonObject.to_user.firstname);

    //    alert(connections + " => [" + jSonObject.to_user.id + "]");
    if (connections.indexOf(jSonObject.to_user.id) === -1) {
        connections = connections + jSonObject.to_user.id + ",";
        $("#connections").append($(newConnection));
    }

    //    alert(jSonObject.to_user.id)
    $.each(jSonObject.discussion, function(i, l) {
        insertDiscussion(l, '', 0);
    });
    $("#discussion").animate({
        scrollTop: $("#discussion")[0].scrollHeight
    }, 100);

    $("#chatText").focus();
}

function loadPlus(dtMin) {
    if (dtMin == "empty") {
        //        alert("empty")
        return;
    }
    //    alert(dtMin)
    url = plusUrl + "/" + dtMin;
    ajaxStart();
    withId = $("#withId").val();
    //alert(withId)
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: {
            withId: withId
        },
        error: function() {
            ajaxStop();
        //console.log("error occurred");
        },
        success: function(data) {
            ajaxStop();
            //console.log("parsing data for with ..");
            console.log(data);
            parseLoadPlus(data);
            $("#withId").val(withId);
            selectUser(withId);
        },
        complete: function(d) {
            ajaxStop();
        }
    });
}

function  parseLoadPlus(data) {
    $(".aToRemove").remove();
    var jSonObject = eval("(" + data + ")");
    var dtMin = jSonObject.dtMin;

    discussion = $("#discussion").html();
    $("#discussion").html("<center class='aToRemove'><a href=\"javascript:loadPlus('" + dtMin + "')\"> Load Plus </a></center>");
    $("#chatingWith").html("");
    htmlChatingWith = getUserDiv(jSonObject);
    //console.log(htmlChatingWith);
    $("#chatingWith").html(htmlChatingWith);
    $("#first_name_with").html(jSonObject.to_user.firstname);
    $.each(jSonObject.discussion, function(i, l) {
        insertDiscussion(l, '', 0);
    });
    $("#discussion").append($(discussion));
//    $("#discussion").animate({
//        scrollTop: $("#discussion")[0].scrollHeight
//    }, 100);
}

function getUserDiv(obj) {
    var u = obj.to_user;
    var t = "<div class='divUser' style='width:100%;'>" +
    " <div class='notSelected'>" +
    "<a href='javascript:popupImage(\"" + tofsUrl + u.tof + "\")'><img src='" + tofsUrl + u.tof + "'/></a>" +
    "<img class='statut" + u.id + "' title='" +
    u.statut +
    "' style='position:absolute; width: 9px; height:9px; margin-left:0px; z-index: 1000;' src='"
    + imgUrl + u.statut + ".png' />" +
    "</div>" +
    "<div class='notSelected'>" +
    "<p>" + u.firstname + " " + u.lastname + "</p>" +
    "<p>" + (u.city !== null ? u.city : "") + ((u.city !== null && u.country !== null) ? ", " : "") + ((u.country !== null) ? u.country : "") + "</p>" +
    "<p>" + ((u.birthday !== null) ? u.birthday : "") + "</p>" +
    //            "<p>" + u.statut + "</p>" +
    "<p  class='logoSocial'>";

    $.each(obj.networks, function(i, l) {
        t += "<a target='_blank' href='http://" + l.url + "'><img src='" + imgUrl + l.logo + "'/>";
        t += "</a>&nbsp;";
    });

    t += "</p>";
    t += "</div></div>";
    //alert(t);
    return t;
}

function insertDiscussion(discussion, effect, scroll) {
    var html = "<div class=\"row\">" +
    "<div class=\"spanG\">" +
    " <img class=\"gravatar\" src=\"" + tofsUrl + discussion.from_user.tof + "\"/>" +
    "</div>" +
    "<div class=\"author\" >" + discussion.from_user.firstname +
    "</div>" +
    "<div class=\"time\">"
    + discussion.dt +
    "</div>" +
    "</div>";

    html += "<div class=\"row\">" +
    "<div class=\"spanG\"></div>" +
    "<div class=\"spanM\" style=\"\">" + discussion.message + "</div>" + "</div>";

    html += "<div class=\"clear hr\"></div>";


    //  html = '<div class="msg">' +
    //                '<div class="chat rounded">' +
    //                '<img class="gravatar" src="' + tofsUrl + discussion.from_user.tof + '" width="23" height="23"/>' +
    //                '<h1 class="author">' + discussion.from_user.firstname + '</h1>' +
    //                '<span class="time">10:44</span>' +
    //                '</div>' +
    //                '<div class="text">' + discussion.message + '</div>' +
    //                '</div>';


    var new_item = $(html).hide();
    $("#discussion").append(new_item);

    if (effect == 'fade') {
        new_item.fadeIn();
    }

    else if (effect == '') {
        new_item.show();
    }

    else {
        new_item.show(effect);
    }

    if (scroll != 0) {
        $("#discussion").animate({
            scrollTop: $("#discussion")[0].scrollHeight
        }, 100);
    }
}

function waterMark(accessor) {
    if ($(accessor).val() == "") {
        $(accessor).val($(accessor).attr("title"));
        $(accessor).addClass("tgl");
    }
    $(accessor).focus(function() {
        if ($(this).val() == $(this).attr("title")) {
            $(this).val("");
            $(this).removeClass("tgl");
        }
    }).blur(function() {
        if ($(this).val() == "") {
            $(this).val($(this).attr("title"));
            $(this).addClass("tgl");
        }
        if ($(this).val() == $(this).attr("title")) {
            $(this).addClass("tgl");
        }
    });
}

function search() {

    url = searchUrl;
    console.info(url);
    // ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: {
            search: $("#search").val()
        },
        error: function() {
        //            ajaxStop();
        },
        success: function(data) {
            //            ajaxStop();
            console.info(data);
            parseSearch(data);
        },
        complete: function(d) {
        //            ajaxStop();
        }
    });
}

function parseSearch(data) {
    //alert(data);
    $("#socialDiv").html(data);

    console.log(data);
}

function tooltipSession() {
    $('#sessionUser').poshytip({
        className: 'tip-twitter',
        content: 'test tooltip !'
    });
}

function force_status(status) {

    url = statusUrl;
    console.info(url);
    // ajaxStart();
    $.ajax({
        async: true,
        cache: false,
        timeout: 120000, // 2 minutes
        type: "POST",
        url: url,
        data: {
            status : status
        },
        error: function(d) {
            //            ajaxStop();
            console.info("ERROR !! "+d);
        },
        success: function(data) {
            //            ajaxStop();
            console.info("dataRet "+ data);
        },
        complete: function(d) {
            //            ajaxStop();
            console.info("comp "+d);
        }
    });
}